
define(['jquery', 'bootstrap', 'backend', 'table', 'form' , 'layer'], function ($, undefined, Backend, Table, Form ,Layer) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init();

            //绑定事件
            $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                var panel = $($(this).attr("href"));
                if (panel.size() > 0) {
                    Controller.table[panel.attr("id")].call(this);
                    $(this).on('click', function (e) {
                        $($(this).attr("href")).find(".btn-refresh").trigger("click");
                    });
                }
                //移除绑定的事件
                $(this).unbind('shown.bs.tab');
            });

            //必须默认触发shown.bs.tab事件
            $('ul.nav-tabs li.active a[data-toggle="tab"]').trigger("shown.bs.tab");

            $('.btn-receive').click(function(){
                Layer.open({
                    type: 2,
                    content:'goods/purchase_create?type=2',
                    area:['900px','600px'],
                    //content: Config.url
                })
            })

            $('.btn-back').click(function(){
                Layer.open({
                    type: 2,
                    content:'goods/purchase_create?type=3',
                    area:['900px','600px'],
                    //content: Config.url
                })
            })

            $('.btn-inventory').click(function(){
                Layer.open({
                    type: 2,
                    content:'goods/purchase_create?type=4',
                    area:['900px','600px'],
                    //content: Config.url
                })
            })

            $('.btn_sns').click(function(){
                alert(111111)
            })

        },
        table: {
            first: function () {
                // 表格1
                var table1 = $("#table1");
                table1.bootstrapTable({
                    url: 'goods/table1',
                    extend: {
                        index_url: '',
                        add_url: 'goods/add',
                        edit_url: 'goods/edit',
                        del_url: '',
                        multi_url: '',
                        table: '',
                    },
                    toolbar: '#toolbar1',
                    sortName: 'id',
                    search: false,
                    columns: [
                        [
                            {field: 'state', checkbox: true, },
                            {field: 'id', title: 'ID'},
                            {field: 'name', title: __('Title'), operate: 'LIKE'},
                            {field: 'is_spec', title: __('Is_spec'), searchList: {"0":__('Is_spec 0'),"1":__('Is_spec 1'),"2":__('Status 2')}, formatter: Table.api.formatter.status},
                            {
                                field: 'is_spec',
                                title: __('Is_spec'),
                                operate: false,
                                formatter: function(row,data){
                                    console.log(row,data)
                                    let html = ''
                                    data.goodsspec.forEach(item=>{
                                        html +=  `<div>${item.spec_name}</div>`
                                    })
                                    //`<span class="icon-open">+</span>${data.goodsspec.length}项`
                                    return html
                                }
                                //formatter: '<table border="1"><tr>111111</tr><th>222222</th><tr>aaaaaa</tr><th>ssssss</th></table>'
                            },
                            //{field: 'spec', title: __('Spec'), operate: 'LIKE'},
                            {field: 'stock', title: __('Inventory'), operate: 'LIKE',formatter: function(row,data){
                                console.log(row,data)
                                let html = ''
                                data.goodsspec.forEach(item=>{
                                    html +=  `<div>${item.stock}</div>`
                            })
                                //`<span class="icon-open">+</span>${data.goodsspec.length}项`
                                return html
                            }},
                            {field: 'stock', title: __('TotalInventory'), operate: 'LIKE'},
                            {field: 'price', title: __('Price'), operate:'BETWEEN'},
                            {field: 'status', title: __('Status'), searchList: {"0":__('隐藏'),"1":__('展示')}, formatter: Table.api.formatter.toggle},
                            //{field: 'url', title: __('Url'), formatter: Table.api.formatter.url},
                            //{field: 'imagewidth', title: __('Imagewidth')},
                            //{field: 'imageheight', title: __('Imageheight')},
                            //{field: 'mimetype', title: __('Mimetype')},
                            {field: 'operate', title: __('Operate'), table: table1, events: Table.api.events.operate, formatter: Table.api.formatter.operate},
                        ]
                    ]
                });

                // 为表格1绑定事件
                Table.api.bindevent(table1);
            },
            second: function () {

                // 表格2
                var table2 = $("#table2");
                table2.bootstrapTable({
                    url: 'goods/table2',
                    extend: {
                        index_url: '',
                        add_url: 'goods/purchase_create?type=1',
                        //add_url: 'goods/create_log?type=1',
                        edit_url: '',
                        del_url: '',
                        multi_url: '',
                        table: '',
                    },
                    toolbar: '#toolbar2',
                    sortName: 'id',
                    search: false,
                    columns: [
                        [
                            {field: 'id', title: 'ID'},
                            {field: 'inout_time', title: __('Inout_time'), formatter: Table.api.formatter.datetime, datetimeFormat:"YYYY-MM-DD", operate: 'RANGE', addclass: 'datetimerange', sortable: true},
                            {field: 'goods_name', title: __('Title')},
                            {field: 'type',title: __('Type'),searchList: {'0': __("Type 0"), '1': __("Type 1"), '2': __("Type 2"), '3': __("Type 3"), '4': __("Type 4")},formatter: Table.api.formatter.normal},
                            {
                                field: 'num',
                                title: __('Inout_num'),
                                operate: false,
                                formatter: function(row,data){
                                    console.log(111111)
                                    if(data.type == 1 || data.type == 3){
                                        data.num = '+'+data.num;
                                        console.log('+'+data.num)
                                    }else if(data.type == 4){
                                        if(data.num > 0){
                                            data.num = '+'+data.num;
                                        }
                                    }else{
                                        data.num = '-'+data.num;
                                    }
                                    let html = data.num
                                    return html
                                }
                            },
                            {field: 'role_type',title: __('Role_type'),searchList: {'0': __("Role_type 0"),'1': __("Role_type 1"), '2': __("Role_type 2"), '3': __("Role_type 3")},formatter: Table.api.formatter.normal},
                            {field: 'role_name', title: __('Role_name')},
                            //{field: 'sn', title: __('Sn'),formatter: Controller.api.formatter.sn},
                            {field: 'sn', title: __('Sn'),
                                formatter: function(row,data){
                                console.log(row,data)
                                let html = '<div class="btn_sn" data-sn="'+data.sn+'" data-id="'+data.id+'">'+data.sn+'</div>'
                                //`<span class="icon-open">+</span>${data.goodsspec.length}项`
                                return html
                            }},
                            {field: 'agent_name', title: __('Agent_name')},
                            {
                                field: 'buttons',
                                // width: "120px",
                                title: '',
                                table: table2,
                                events: Table.api.events.operate,
                                buttons: [
                                    {
                                        name: 'ajax',
                                        text: __('查看详情'),
                                        title: __('查看详情'),
                                        classname: 'btn btn-xs btn-success btn-magic btn-dialog',
                                        // icon: 'fa fa-magic',
                                        url: 'goods/log_detail/ids/{ids}',
                                        extend: 'data-area=["100%","100%"]',
                                    }
                                ],
                                formatter: Table.api.formatter.buttons
                            },
                            //操作栏,默认有编辑、删除或排序按钮,可自定义配置buttons来扩展按钮
                            //{
                            //    field: 'operate',
                            //    width: "150px",
                            //    title: __('Operate'),
                            //    table: table2,
                            //    events: Table.api.events.operate,
                            //    buttons: [
                            //        {
                            //            name: '查看详情',
                            //            title: __('查看详情'),
                            //            classname: 'btn btn-xs btn-info btn-click',
                            //            //icon: 'fa fa-leaf',
                            //            // dropdown: '更多',//如果包含dropdown，将会以下拉列表的形式展示
                            //            click: function (data) {
                            //                Layer.alert("点击按钮执行的事件");
                            //            }
                            //        },
                            //    ],
                            //    formatter: Table.api.formatter.operate
                            //},
                        ]
                    ]
                });
                $(document).on('click','.btn_sn' ,function (e) {
                   console.log( $(this).data('sn'))
                    Layer.open({
                        type: 2,
                        content:'goods/purchaseDetail?sn='+$(this).data('sn')+'&ids='+$(this).data('id'),
                        area:['100%','100%'],
                        //content: Config.url
                    })
                })
                // 为表格2绑定事件
                Table.api.bindevent(table2);
            }
        },
        add: function () {
            Controller.spec();
            Controller.api.bindevent();
        },
        edit: function () {


            data = eval('(' + Config.data + ')');
            Controller.spec();

            // 初始化加载数据
            Controller.create_table(false);
            Controller.api.bindevent();
            Controller.is_show();
        },
        purchase_create: function () {
            Controller.api.bindevent();
        },
        receive: function () {
            Controller.api.bindevent();
        },
        log_detail: function () {
            $('#popup').click(function(){
                alert('aaaaaa');
            })

            Controller.api.bindevent();
        },

        // 加载已输入的规格数据
        load_data: function(data){
            $.each(data, function(k, v){
                $('input[name="spec_data[' + k + '][price]"]').val(v.price);
                $('input[name="spec_data[' + k + '][cost_price]"]').val(v.cost_price);
                $('input[name="spec_data[' + k + '][stock]"]').val(v.stock);
                if(v.spec_image != '')
                {
                    $('input[name="spec_data[' + k + '][spec_image]"]').val(v.spec_image);

                    if(typeof(v.spec_image) != 'undefined')
                    {
                        var image_html = `
                            <li class="col-xs-3">
                                <a href="` + v.spec_image + `" data-url="` + v.spec_image + `" target="_blank" class="thumbnail">
                                    <img src="` + v.spec_image + `" onerror="this.src='https://tool.fastadmin.net/icon/'+'` + v.spec_image + `'.split('.').pop()+'.png';this.onerror=null;" class="img-responsive">
                                </a>
                                <a href="javascript:;" class="btn btn-danger btn-xs btn-trash"><i class="fa fa-trash"></i></a>
                            </li>`;
                        $('input[name="spec_data[' + k + '][spec_image]"]').prev().html(image_html);
                    }
                }
            })
        },

        // 规格操作
        spec: function(){
            // 点击添加规格
            $('.add_group_btn button').click(function(){
                $('.add_group_btn').addClass('hide');
                $('.add_group_form').removeClass('hide');
            })

            // 取消添加规格
            $('.add_group_no').click(function(){
                $('.add_group_btn').removeClass('hide');
                $('.add_group_form').addClass('hide');
            })

            // 确定添加规格
            $('.add_group_yes').click(function(){
                var group_name = $('.add_group_name').val();
                var item_name = $('.add_group_value').val();
                group_name = $.trim(group_name);
                item_name = $.trim(item_name);

                if(!Controller.check_name(group_name) || !Controller.check_name(item_name))
                {
                    return;
                }

                if($('.group_name:contains("' + group_name + '")').length > 0)
                {
                    layer.msg('已添加【' + group_name + '】，不可重复添加！');
                    return;
                }

                var group_id = '';
                var item_id = '';

                $('.add_group_btn').removeClass('hide');
                $('.add_group_form').addClass('hide');

                $('.add_group_name').val('');
                $('.add_group_value').val('');

                var group_html = $('#group_html').html();
                group_html = group_html.replace('{group_name}', group_name);
                group_html = group_html.replace('{group_id}', group_id);

                var item_html = $('#item_html').html();
                item_html = item_html.replace('{item_name}', item_name);
                item_html = item_html.replace('{item_id}', item_id);

                $('.add_group_btn').before(group_html);
                $('.group_item:last .item_add_btn').before(item_html);

                Controller.create_table();
                Controller.is_show();
            })

            // 添加规格值
            $(document).on('click', '.item_add_btn span.input-group-addon', function(){
                var item_name = $(this).prev().val();
                item_name = $.trim(item_name);
                var item_id = '';

                if(!Controller.check_name(item_name))
                {
                    return;
                }

                if($(this).parents('.group_item').find('.spec_item:contains("' + item_name + '")').length > 0)
                {
                    layer.msg('已添加【' + item_name + '】，不可重复添加！');
                    return;
                }

                $(this).prev().val('');
                var item_html = $('#item_html').html();
                item_html = item_html.replace('{item_name}', item_name);
                item_html = item_html.replace('{item_id}', item_id);
                $(this).parent().before(item_html);
                Controller.create_table();
            })

            // 删除规格组
            $(document).on('click', '.group_item .close', function(){
                $(this).parents('.group_item').remove();
                Controller.create_table();
                Controller.is_show();
            })

            // 删除规格值
            $(document).on('click', '.del_item', function(){
                $(this).parents('.spec_item').remove();
                Controller.create_table();
            })

            // 批量设置
            $(document).on('click', '.all_set', function(){
                var all_set = $(this).parent();
                $('.spec_table tbody tr').each(function(k1, v1){
                    var tr = $(this);
                    all_set.find('input').each(function(k, v){
                        tr.find('input:eq(' + k + ')').val($(v).val());
                    })
                    all_set.find('.plupload-preview').each(function(k, v){
                        tr.find('.plupload-preview:eq(' + k + ')').html($(v).html());
                    })
                })
            })
        },

        // 判断是否显示表格
        is_show: function(){
            if($('.group_item').length > 0)
            {
                $('.group_list').removeClass('hide');
            }
            else
            {
                $('.group_list').addClass('hide');
            }
        },

        // 判断规格名称是否包含特殊关键字
        check_name: function(name){
            if(name == '')
            {
                layer.msg('不能为空！');
                return false;
            }

            if(name.indexOf('"') >= 0 || name.indexOf("'") >= 0 || name.indexOf('`') >= 0)
            {
                layer.msg('不能包含关键字： \' " `');
                return false;
            }
            return true;
        },

        // 创建表格
        create_table: function(isset = true) {
            if(isset)
            {
                Controller.set_data();
            }

            var table = Controller.get_table();
            var thead = $('<thead></thead>');
            var tr = $('<tr></tr>');
            $('.group_item').each(function(k, v){
                if($(this).find('.spec_item').length == 0)
                {
                    return true;
                }

                tr.append('<th>' + $(this).find('.group_name').html() + '</th>');
            })
            tr.append($('.table_header').html());
            thead.append(tr);

            // 加入每行的公共提交表单
            var id_index = 0;
            table.find('tr').each(function(k, v){
                var table_html = $('#table_html').html();
                var spec_name = '';

                $(v).find('td').each(function(k2, v2) {
                    spec_name += $('.group_name').eq(k2).html() + '`' + $(v2).html() + '`';
                })

                if(spec_name.length > 0)
                {
                    spec_name = spec_name.substring(0, spec_name.length-1);
                }

                table_html = table_html.replace(new RegExp('{spec_name}', "g"), spec_name);
                table_html = table_html.replace(new RegExp('{i}', "g"), id_index);
                id_index++;

                table.find('tr').eq(k).append(table_html);
            })

            $('.spec_table').html(thead);
            $('.spec_table').append(table);

            if(isset)
            {
                Form.events.plupload($("form"));    // 重新渲染上传插件
                Form.events.faselect($(".spec_table"));     // 重新渲染选择附件插件
            }

            // 载入数据
            Controller.load_data(data);
        },

        // 更新data
        set_data: function(){
            var tmp_data = {};
            $('.spec_table tbody input[type="text"],.spec_table tbody input[type="hidden"]').each(function(k, v){
                var name = $(v).attr('name');
                var tmp_key = name.match(/([^\[]+`)+[^\]]+/);
                tmp_key = tmp_key[0];
                var tmp_column = name.match(/[^\[\]]+/g);
                tmp_column = tmp_column[2];

                if($(v).val() != '')
                {
                    if(tmp_data[tmp_key] == undefined)
                    {
                        tmp_data[tmp_key] = {};
                    }

                    tmp_data[tmp_key][tmp_column] = $(v).val();
                }
            })
            data = tmp_data;
            console.log(data);
        },

        // 获取指定规格值有多少行数据
        get_count: function(spec_item){
            var i = 0;
            spec_item.parents('.group_item').nextAll().each(function(k, v){
                var tmp = $(v).find('spec_item').length;
                if(tmp > 0)
                {
                    if(i == 0)
                    {
                        i = 1;
                    }

                    i *= tmp;
                }
            })

            return i;
        },

        // 递归获取表格html
        get_table: function(data = $('<tbody></tbody>'), obj = '', i = 0){
            if(obj == '')
            {
                obj = $('.group_item:first');
                if(obj.length == 0)
                {
                    return $('<tbody></tbody>');
                }
            }

            var item = obj.find('.spec_item');
            if(item.length == 0)
            {
                return $('<tbody></tbody>');
            }

            var result_data = $('<tbody></tbody>');
            item.each(function(k1, v1){
                var tmp_data = $('<tbody></tbody>');

                if(data.find('tr').length > 0)
                {
                    data.find('tr').each(function(k2,v2){
                        var tmp_tr = $(v2).prop("outerHTML");
                        tmp_tr = $(tmp_tr);
                        tmp_tr.append('<td>' + $(v1).find('.item_name').html() + '</td>');
                        tmp_data.append(tmp_tr);
                    })
                }
                else
                {
                    var tmp_tr = $('<tr><td>' + $(v1).find('.item_name').html() + '</td></tr>');
                    tmp_data.append(tmp_tr);
                }

                if(obj.next().hasClass('group_item'))
                {
                    var tmp = Controller.get_table(tmp_data, obj.next(), (i + 1));

                    // 合并单元格
                    tmp.find('tr:first').find('td').eq(i).attr('rowspan', tmp.find('tr').length);
                    tmp.find('tr').not(':first').find('td:eq(' + i +')').css('display', 'none');

                    result_data.append(tmp.html());
                }
                else
                {
                    result_data.append(tmp_data.html());
                }
            })

            return result_data;
        },
        api: {
            bindevent: function () {

                $(document).on("change", "input[name='row[role_type]']", function(){
                    console.log($(this).val())
                    var role_type = $(this).val();
                    if(role_type == '1'){
                        $("#time_limit_1").show();
                    }else if(role_type == '2'){
                        $("#time_limit_1").hide();
                    }
                });

                Form.api.bindevent($("form[role=form]"));
            },
            formatter: {
                sn: function (value, row, index) {
                    //这里手动构造URL
                    url = "goods/purchaseDetail?" + this.field + "=" + value;

                    //方式一,直接返回class带有addtabsit的链接,这可以方便自定义显示内容
                    //return '<a href="' + url + '" class="label label-success addtabsit" title="' + __("Search %s", value) + '">' + __('Search %s', value) + '</a>';

                    //方式二,直接调用Table.api.formatter.addtabs
                    this.url = url;
                    return Table.api.formatter.addtabs.call(this, value, row, index);
                }
            }
        }
    };
    return Controller;
});

//define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
//
//    var Controller = {
//        index: function () {
//            // 初始化表格参数配置
//            Table.api.init({
//                extend: {
//                    index_url: 'goods/index' + location.search,
//                    add_url: 'goods/add',
//                    edit_url: 'goods/edit',
//                    del_url: 'goods/del',
//                    multi_url: 'goods/multi',
//                    import_url: 'goods/import',
//                    table: 'goods',
//                }
//            });
//
//            var table = $("#table");
//
//            // 初始化表格
//            table.bootstrapTable({
//                url: $.fn.bootstrapTable.defaults.extend.index_url,
//                pk: 'id',
//                sortName: 'id',
//                columns: [
//                    [
//                        {checkbox: true},
//                        {field: 'id', title: __('Id')},
//                        {field: 'title', title: __('Title'), operate: 'LIKE'},
//                        {field: 'is_spec', title: __('Is_spec')},
//                        {field: 'spec', title: __('Spec'), operate: 'LIKE'},
//                        {field: 'price', title: __('Price'), operate:'BETWEEN'},
//                        {field: 'inventory_warn', title: __('Inventory_warn')},
//                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
//                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
//                    ]
//                ]
//            });
//
//            // 为表格绑定事件
//            Table.api.bindevent(table);
//        },
//        add: function () {
//            Controller.api.bindevent();
//        },
//        edit: function () {
//            Controller.api.bindevent();
//        },
//        api: {
//            bindevent: function () {
//                Form.api.bindevent($("form[role=form]"));
//            }
//        }
//    };
//    return Controller;
//});
